import { ElMessage } from "element-plus";
import { ref } from "vue";
// import { exportXLSX } from "@u/file/index";
import type { FormItem } from "../components/Form/index";
import { UseTableParam, UseWirteTableReturn, DialogProps } from "./type";

export function useWriteTable(tableConfig: UseTableParam): UseWirteTableReturn {
  const {
    // tableRef,
    searchFormConifg,
    // tableConifg,
    getDataAPI,
    addDataAPI,
    editDataAPI,
    delDataAPI,
  } = tableConfig;

  const tableData = ref<object[]>([]);
  const searchFormData = ref<Record<string, unknown>>({});

  // 编辑行的下标
  const editRowIndexArr = ref<number[]>([]);

  searchFormConifg?.value.forEach((item: FormItem) => {
    //表单项中有配置默认值的，将其赋值给表单
    if (item.defaultValue) {
      searchFormData.value[item.prop] = item.defaultValue;
    }
  });

  //编辑行数据
  const editHandle = (data: Record<string, unknown>, index: number) => {
    if (!editRowIndexArr.value.includes(index)) {
      editRowIndexArr.value.push(index);
    } else {
      submit(data);
      editRowIndexArr.value.splice(index, 1);
    }
  };

  const paginationProps = ref({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  });

  const viewFormDialogProps = ref<DialogProps>({
    dialogVisible: false,
    title: "详情弹窗",
    formData: {},
  });

  //打开详情弹窗
  const handleOpenView = (formData: object) => {
    viewFormDialogProps.value.dialogVisible = true;
    viewFormDialogProps.value.formData = formData;
  };

  //新增行数据
  const addHandle = () => {
    if (editRowIndexArr.value.length) {
      for (let i = 0; i < editRowIndexArr.value.length; i++) {
        editRowIndexArr.value[i] = editRowIndexArr.value[i] + 1;
      }
    }
    tableData.value.unshift({});
    editRowIndexArr.value.push(0);
  };

  //查询
  const searchHandle = () => {
    getTableList();
  };

  //重置
  const resetHandle = () => {
    searchFormData.value = {};
  };

  const handleSizeChange = (val: number) => {
    paginationProps.value.pageSize = val;
    getTableList();
  };

  const handleCurrentChange = (val: number) => {
    paginationProps.value.currentPage = val;
    getTableList();
  };

  //删除
  const delHandle = (id: number | string) => {
    if (delDataAPI) {
      delDataAPI(id)
        .then((res: any) => {
          const { code } = res;
          if (code === 200) {
            ElMessage({
              message: "删除成功",
              type: "success",
            });
            getTableList();
          }
        })
        .catch((err) => {
          ElMessage({
            message: err,
            type: "error",
          });
        });
    }
  };

  //导出
  const exportHandle = () => {
    // exportXLSX(tableData.value, tableConifg.value);
  };

  // 提交
  const submit = (formData: Record<string, unknown>) => {
    let fun = null;
    let msg = "";
    if (formData.id) {
      fun = editDataAPI;
      msg = "编辑";
    } else {
      fun = addDataAPI;
      msg = "新增";
    }
    if (fun) {
      fun(formData)
        .then((res: any) => {
          const { code } = res;
          if (code === 200) {
            ElMessage({
              message: `${msg}成功`,
              type: "success",
            });
            getTableList();
          }
        })
        .catch((err) => {
          ElMessage({
            message: err,
            type: "error",
          });
        });
    }
  };

  //查询数据
  const getTableList = () => {
    getDataAPI({
      ...searchFormData.value,
      currentPage: paginationProps.value.currentPage,
      pageSize: paginationProps.value.pageSize,
    }).then((res: any) => {
      const { code, result, total } = res;
      if (code === 200) {
        tableData.value = result;
        paginationProps.value.total = total;
      }
    });
  };

  return {
    editRowIndexArr,
    paginationProps,
    viewFormDialogProps,
    tableData,
    searchFormData,
    addHandle,
    editHandle,
    getTableList,
    searchHandle,
    resetHandle,
    submit,
    delHandle,
    exportHandle,
    handleSizeChange,
    handleCurrentChange,
    handleOpenView,
  };
}
